<template>
    <div id="app">
        <transition :name="$store.state.states">
            <keep-alive>
                <router-view class="child-view"></router-view>
            </keep-alive>
        </transition>
        <el-amap vid="app-map" v-show="false" :plugin="plugins"></el-amap>
    </div>
</template>

<script>
    /* eslint-disable no-unused-vars,no-console */
    import utils from './utils'
    import ReconnectingWebSocket from 'reconnectingwebsocket'


    export default {
        name: 'app',
        components: {},
        data() {
            let self = this
            return {
                geo: null,
                timer: null,
                transition: 'fade',
                lng: 0,
                lat: 0,
                center: [],
                loaded: false,
                plugins: [{
                    pName: 'Geolocation',
                    events: {
                        init(o) {
                            self.geo = o;
                        }
                    },
                    panToLocation: false,
                    showButton: false,
                }, {
                    pName: 'AMap.PlaceSearch',
                    events: {
                        init(s) {
                            window.app.$search = s;
                        }
                    }
                }, {
                    pName:"AMap.Driving",
                    events:{
                        init(d){
                            window.app.$driver = d;
                        }
                    }
                }],
                socket: null,
                heartbeatTimer: null,
            }
        },
        watch: {
            // '$route'(to, from) {
            //     if (from.meta && from.meta.direction === 'slide-left') {
            //         this.transition = 'slide-right';
            //         if (to.meta.direction === 'slide-left') {
            //             this.transition = to.meta.direction
            //         }
            //         if (this.isBack) {
            //             this.transition = 'slide-right'
            //         }
            //         // if (
            //         //     (to.name === 'like' && from.name === 'likeCompany') ||
            //         //     (to.name === 'articleMine' && from.name === 'editArticleMine')
            //         // ) {
            //         //     this.transition = 'slide-right';
            //         // }
            //     } else {
            //         this.transition = to.meta.direction || 'fade';
            //     }
            // }
        },
        methods: {
            initTimer() {
                let self = this;
                this.timer = setInterval(() => {
                    if (self.geo) {
                        self.geo.getCurrentPosition((status, result) => {
                            if (result && result.position) {
                                // console.log(result);
                                let component = result.addressComponent
                                let city = component.city ? component.city : component.province
                                self.$store.commit('updateLocation', {
                                    lat: result.position.lat,
                                    lng: result.position.lng,
                                    address: result.formattedAddress,
                                    city: city
                                })
                                self.loaded = true;
                                self.$nextTick();
                            }
                        });
                    }
                }, 2000);
            },
            stopTimer() {
                if (this.timer) {
                    clearInterval(this.timer)
                }
            },
            initSocket() {
                let socket = new ReconnectingWebSocket("ws://jsshop.kooki.cn:7007")
                socket.onopen = this.onSocketOpen.bind(this);
                socket.onmessage = this.onSocketMessage.bind(this);
                socket.onclose = this.onSocketClose.bind(this);
                this.socket = socket;
                window.onbeforeunload = () => {
                    socket.close();
                    this.$store.commit('updateSocket', {socket: null});
                }
                this.$store.commit('updateSocket', {socket: socket})

            },
            onSocketOpen() {
                this.startHeartBeat()

            },

            startHeartBeat() {
                this.heartbeatTimer = setInterval(() => {
                    if (this.socket.state != WebSocket.CLOSED || this.socket.state != WebSocket.CLOSED) {
                        // let data = utils.stringToBytes('{mid:24}');
                        this.socket.send('{mid:24}')
                    }
                }, 10000)
            },


            onSocketMessage(ret) {
                console.log(ret)
                if (ret.data == '[Web]Welcome to WebSocket Server!\n\n') {
                    console.log('----welcome')
                    if (utils.checkLogin()) {
                        this.$store.dispatch('socketLogin')
                    }
                } else {
                    let result = ret.data.replace('\n\n', '');
                    try {
                        let data = JSON.parse(result)
                        this.$store.dispatch('handleSocketMessage', data)
                    } catch (e) {
                        console.log(e)
                    }
                }
            },
            onSocketClose() {
                this.$store.commit('updateSocket', {socket: null});
                this.socket.close();
                this.stopTimer();
                // if (this.socket.)
            }
        },
        mounted() {
            this.initTimer();
            this.initSocket();
        },
        destroyed() {

            if (this.socket) {
                this.socket.close()
            }
        }
    }
</script>

<style lang="less">
    @import url('https://at.alicdn.com/t/font_870013_j5pl5rx0wq.css');

    html, body, #app {
        height: 100%;
    }

    .child-view {
        position: fixed;
        width: 100%;
        height: 100%;
        transition: all .377s ease;
        box-sizing: border-box;
        overflow: auto;
        background: #fff;
    }

    .fade-enter-active, .fade-leave-active {
        transition: opacity .5s;
    }

    .fade-enter, .fade-leave-to {
        opacity: 0;
    }

    .slide-left-enter,
    .slide-right-leave-active {
        opacity: 0;
        -webkit-transform: translate(100%, 0);
        transform: translate(100%, 0);
    }

    .slide-left-leave-active,
    .slide-right-enter {
        opacity: 0;
        -webkit-transform: translate(-100%, 0);
        transform: translate(-100% 0);
    }

    .turn-on-enter {
        transform: translate3d(100%, 0, 0);
    }

    .turn-on-leave-to {
        /* transform: translate3d(-20%, 0, 0); */
    }

    .turn-on-enter-active,
    .turn-on-leave-active {
        transition: transform 0.4s ease;
    }

    .turn-off-enter {
        /* transform: translate3d(-20%, 0, 0); */
    }

    .turn-off-leave-to {
        transform: translate3d(100%, 0, 0);
    }

    .turn-off-enter-active,
    .turn-off-leave-active {
        transition: transform 0.4s ease;
    }

    .turn-off-leave-active {
        z-index: 2;
    }

</style>
